<template>
    <common-list>
        <!-- 头部搜素start -->
        <common-search slot="search" @search="handleQuery" @reset="resetQuery">
            <el-form @submit.native.prevent :model="query" ref="queryForm" v-show="showSearch" :inline="true"
                label-width="65px">
                <el-form-item label="分类名称">
                    <common-input v-model="query.orgName" clearable @enter="handleQuery" />
                </el-form-item>
            </el-form>
        </common-search>

        <!-- 按钮组织start -->
        <el-row slot="tools" :gutter="10" class="mb8">
            <el-col :span="1.5" v-hasPermi="['apisecurity:organization:add']" >
                <el-button type="primary" plain icon="el-icon-plus" @click="edit('add', null)" :disabled="list.length !== 0">新增一级分类
                </el-button>
                <content-tip :tipType="'appliction_content'" popoverWidth="180"></content-tip>
            </el-col>
        </el-row>

        <!--列表 start-->
        <common-table slot="content" isSetRowKey :data="list" style="width: 100%" row-key="orgId" default-expand-all>
            <el-table-column prop="orgName" label="分类/应用名称" show-overflow-tooltip>
                <template slot-scope="{ row }">
                    {{row.orgName || row.appName}}
                </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" show-overflow-tooltip>
                <template slot-scope="{ row }">
                    {{row.type === '0' ? '分类' : '应用'}}
                </template>
            </el-table-column>
            <el-table-column prop="orderNum" label="排序"></el-table-column>
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
            <el-table-column label="操作" align="left" width="230px">
                <template slot-scope="{ row }">
                    <el-button type="text" @click="edit('add', row)" v-hasPermi="['apisecurity:organization:add']" v-if="row.type === '0' && row.isType">新增下级分类</el-button>
                    <el-button type="text" @click="handleAddApplication('add', row)" v-hasPermi="['apisecurity:organization:add']" v-if="(!row.children && row.type === '0') || !row.isType">新增应用</el-button>
                    <el-button type="text" @click="edit('edit', row)" v-hasPermi="['apisecurity:organization:edit']">编辑</el-button>
                    <el-button type="text" @click="handleDelete(row)" v-hasPermi="['apisecurity:organization:remove']">删除</el-button>
                </template>
            </el-table-column>
        </common-table>

        <add-type ref="editTypeDialog" @refresh="getList"></add-type>
        <add-application ref="editAppDialog" @refresh="getList"></add-application>
    </common-list>
</template>

<script>
import BaseList from "@/mixins/BaseList";
import AddType from './components/typeAdd'
import AddApplication from './components/applicationAdd'
import ContentTip from "@/views/analysisCenter/log/ContentTip/index.vue";
import { deepClone } from "@/utils/";
import { list, remove, checkBeforeDelete } from '@/api/apisecurity/applicationType/applicationType'
export default {
    components: { AddType, AddApplication, ContentTip },
    mixins: [BaseList],
    props: {},
    data() {
        return {
            addList: [],
            showSearch: true, // 查询部分显示
            loading: false, // table 加载中
            selectionIds: "", // 列表选中数据id
            single: true, // 非单个禁用
            multiple: true, // 非多个禁用
            query: {
                pageNum: 1,
                pageSize: 10,
                orgName: null,
            }, // 查询条件
            list: [],
            editDeptId: 0,
            key: "orgId",
            configItem: sp_config
        };
    },
    watch: {},
    computed: {},
    methods: {
        /**
         * 获取列表
         */
        getList() {
            this.loading = true;
            let query = { ...this.query };
            list(query)
                .then((res) => {
                    if (res && res.code === 200) {
                        this.list = this.getTreeData(res.data, "orgId");
                        this.addList = deepClone(this.list);
                        // console.log(this.getTreeData(this.list, []))

                    } else {
                        this.list = [];
                        this.handleListTips(res);
                    }
                })
                .finally(() => (this.loading = false));
        },

        getTreeData(data, id, parentId, children) {
            let config = {
                id: id || 'id',
                parentId: parentId || 'parentId',
                childrenList: children || 'children'
            };

            var childrenListMap = {};
            var nodeIds = {};
            var tree = [];

            for (let d of data) {
                let parentId = d[config.parentId];
                if (childrenListMap[parentId] == null) {
                    childrenListMap[parentId] = [];
                }
                nodeIds[d[config.id]] = d;
                childrenListMap[parentId].push(d);
            }

            for (let d of data) {
                let parentId = d[config.parentId];
                if (nodeIds[parentId] == null) {
                    tree.push(d);
                }
            }

            for (let t of tree) {
                adaptToChildrenList(t);
            }

            function adaptToChildrenList(o, path) {
                let fullPath = path ? deepClone(path) : []
                if (childrenListMap[o[config.id]] !== null) {
                    o[config.childrenList] = childrenListMap[o[config.id]];
                }
                if(o.parentId) {
                    fullPath.push(o.parentId)
                    o.fullPath = fullPath
                }
                o.isType = true
                if (o[config.childrenList]) {
                    for (let c of o[config.childrenList]) {
                        if(c.type === '1') o.isType = false
                        adaptToChildrenList(c, fullPath);
                    }
                }
            }
            return tree;
        },
        /**
         * 查询
         */
        handleQuery() {
            this.query.pageNum = 1;
            this.getList();
        },
        /**
         * 重置查询
         */
        resetQuery() {
            this.query = this.$options.data().query;
        },
        /**
         * 添加/编辑
         */
        edit(editType, row) {
            if(row && row.type === '0') {
                this.$refs.editTypeDialog.show({ editType, ...row });
            } else if(row && row.type === '1') {
                this.handleAddApplication(editType, row)
            } else {
                this.$refs.editTypeDialog.show({editType});
            }
            
        },

        handleAddApplication(editType, row) {
            this.$refs.editAppDialog.show(row ? { editType, ...row } : {editType});
        },
        /**
         * 详情
         */
        // detail(row) {
        //     if (row && row.deptId > 0) {
        //         this.editDeptId = row.deptId;
        //     }
        //     this.$refs.orgDetail.show(row ? { ...row } : {});
        // },
        /**
         * 删除
         */
        deleteData(row) {
            // remove({ orgId: row.orgId }).then((res) => {
            //             if (res && res.code === 200) {
            //                 this.getList();
            //                 this.$GlobalSuccessMessage("删除成功");
            //             } else {
            //                 this.$GlobalErrorConfirm("删除失败", res.msg).then();
            //             }
            //         });


            this.$GlobalDeleteConfirm().then(() => {
                    remove({ orgId: row.orgId }).then((res) => {
                        if (res && res.code === 200) {
                            this.getList();
                            this.$GlobalSuccessMessage("删除成功");
                        } else {
                            this.$GlobalErrorConfirm("删除失败", res.msg).then();
                        }
                    });
                }).catch(() => { });

            // if (row && row.status == 0) {
            //     this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
            // } else {
            //     let msg;
            //     if (row.children && row.children.length > 0)
            //         msg = "该分类下包含下级，是否继续操作？";
                
            // }
        },
        /**  删除前校验 */
        beforeDeleteForCheck(ids) {
            // console.log("ids====>", ids);
            return new Promise((resolve, reject) => {
                checkBeforeDelete({ orgId: ids })
                    .then((res) => {
                        if (res && res.code === 200) {
                            resolve(res);
                        } else {
                            reject(res);
                        }
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
    },
    created() {
        this.getList();
    },
    mounted() { },
};
</script>
<style lang="scss" scoped>
</style>
